#include "endwidget.h"
#include "QMessageBox"
#include "sysconf.h"
#include <QtXml/QDomDocument>
#include <QTextStream>



extern bool createDatamapFile(const QString &filename,QString &error);
extern bool createStartup(const QString &filename,QString &error);
extern bool crateCID(const QString &filename);

extern Channel chn[2];
extern _61850 m61850;
extern QList<DevConf> confDevList;

EndWidget::EndWidget(QWidget *parent) :
    QWidget(parent)
{
    setupUi(this);

    connect(backNext,SIGNAL(clicked()),this,SLOT(back()));
    connect(nextBtn,SIGNAL(clicked()),this,SLOT(createFile()));
}

void EndWidget::refreshData()
{
    QString str,str1,str2;
    int i=0;

    str=QString("配置如下:\n--------------------\n设备数:%1\n通道1设备数:%2,通道2设备数:%3\nIEDName:%4\n--------------------\n")
            .arg(chn[0].sysdev.size()+chn[1].sysdev.size())
            .arg(chn[0].sysdev.size())
            .arg(chn[1].sysdev.size())
            .arg(m61850.iedName);
    str1=QString("通道1---端口:%1,波特率:%2\n").arg(chn[0].com_name).arg(chn[0].baud);
    for(i=0;i<chn[0].sysdev.size();i++)
    {
        str1.append("设备类型:").append(chn[0].sysdev.at(i).dev_type)
                .append(",设备地址:").append(QString::number(chn[0].sysdev.at(i).devAddr))
                .append("\n");
    }
    str2=QString("--------------------\n通道2---端口:%1,波特率:%2\n").arg(chn[1].com_name).arg(chn[1].baud);
    for(i=0;i<chn[1].sysdev.size();i++)
    {
        str2.append("设备类型:").append(chn[1].sysdev.at(i).dev_type)
                .append(",设备地址:").append(QString::number(chn[1].sysdev.at(i).devAddr))
                .append("\n");
    }
    str2.append("--------------------");

    str.append(str1).append(str2);
    textEdit->setText(str);


}

void EndWidget::next()
{
    emit mystep(1);

}

void EndWidget::back()
{
    emit mystep(-1);
}


void EndWidget::createFile()
{


    QString error;
    if(!xml.parseFile("./config/channel.cfg",error))
    {
        qDebug("%s",qPrintable(error));
        QMessageBox::about(NULL,"提示","加载channel.cfg模板文件失败!\n");
        return;
    }
    if(!xml.writeXml("./dist/integrate/channel.cfg",error))
    {
        qDebug("%s",qPrintable(error));
        QMessageBox::about(NULL,"提示","生成channel.cfg失败!\n");
        return;
    }

    if(!createDatamapFile("./dist/mmslite/datamap.cfg",error))
    {
        qDebug("%s",qPrintable(error));
        QMessageBox::about(NULL,"提示","生成datamap.cfg失败!\n");
        return;
    }
    if(!crateCID("./dist/mmslite/titans_ied.cid"))
    {
        qDebug("create failed:titans_ied.cid ");
        return;
    }
    if(!createStartup("./dist/mmslite/startup.cfg",error))
    {
        qDebug("%s",qPrintable(error));
        return;
    }



    QMessageBox::about(NULL,"提示","生成成功!\n");
}



